// 公共的form表单文件，一键式生成
import IconFont from '@/components/IconFont';
import FormContent from './FormContent';
import BatchSearch from '@/components/BatchSearch';
import QuickSearch from './QuickSearch';
import { customTrimFunc } from '@/utils/utils.jsx';
import { Button, Form, Space, Popover } from 'antd';
import { useEffect, useState } from 'react';
import { quickQueryLabelGetByCode } from './service.js';
import styles from './index.module.less';

/**
 * 
 * @param {*}  query desc: 查询参数
 * @param {*}  formArr desc: 渲染数据，生成表单的数据源，对象数组[{ itemConfig: { name: '' }, elConfig: { formType, placeHolder, ...}}]
 * @param {*}  formConfig desc: 外层form的设置参数
 * @param {*}  clickSearch desc: 点击查询事件
 * @param {*}  clickReset desc: 点击重置事件
 * @param {*}  resetKey desc: 需要触发表单更新时传递此参数，例如需要接收url跳转传参
 * @param {*}  showExpand desc: 是否有展开收起设置
 * @param {*}  showKeys desc: 收起时展示的字段集合
 * @param {*}  clickExpand desc: 点击收起展示按钮事件
 * @param {*}  showQuickSearch desc: 是否有快捷查询功能
 * @param {*}  ignoreQuickKeys desc: 另存为快捷擦查询时需要忽略的值，即判空时不包含该字段
 * @param {*}  quickSearchCode desc: 快捷查询储存场景值
 * @returns 
 */

const FormRender = (props) => {

  const { query, formArr = [], formConfig = {}, resetKey, showExpand = false, showKeys = [], showQuickSearch = false, ignoreQuickKeys = [], quickSearchCode, clickSearch, clickReset, clickExpand } = props;

  const { style, customSearchBtn } = formConfig;

  const [form] = Form.useForm();

  const [expand, setExpand] = useState(true);

  const [batchKey, setBatchKey] = useState();

  const [batchVisible, setBatchVisible] = useState(false);

  const [quickList, setQuickList] = useState([]);

  useEffect(() => {
    if(showQuickSearch) {
      getQuickList();
    }
  }, [])

  useEffect(() => {
    form.resetFields();
  }, [resetKey])

  useEffect(() => {
    clickExpand && clickExpand();
  }, [expand])

  useEffect(() => {
    window.dispatchEvent(new Event('resize'));
  }, [quickList])

  //获取当前快捷查询条件
  const getQuickList = async () => {
    const { success, data } = await quickQueryLabelGetByCode({
      code: quickSearchCode
    })
    if (success && data.param) {
      const arr = JSON.parse(data.param);
      setQuickList(arr);
    }
  }

  const onFinish = (values) => {
    //去除空格
    const val = customTrimFunc({ ...values });
    clickSearch(val);
  };

  //重置
  const onReset = () => {
    clickReset();
  };

  //自定义组件赋值
  const handleSetForm = (formKey, val) => {
    form.setFieldsValue({ [formKey]: val })
  }

  //点击展开收起
  const handleExpand = () => {
    setExpand(!expand);
    clickExpand && clickExpand(expand);
  }

  //点击批量输入
  const handleBatchInput = (val) => {
    setBatchKey(val);
    setBatchVisible(true);
  }



  //批量输入弹框
  const searchProps = {
    searchVisible: batchVisible,
    batchSearchLabel: batchKey,
    handleCancel: () => {
      setBatchVisible(false);
    },
    handleOk: (value) => {
      form.setFieldsValue({
        [batchKey]: value
      })
      setBatchVisible(false);
    }
  }

  //快捷查询弹框
  const QuickSearchProps = {
    form,
    quickList,
    ignoreQuickKeys,
    quickSearchCode,
    setQuickList,
    clickQuickSearch(val) {
      clickSearch(val);
      form.setFieldsValue(val);
      clickExpand && clickExpand(expand);
    }
  }

  const formStyle = {
    background: '#fff',
    padding: '16px',
    borderRadius: '4px'
  }

  const formItemStyle = {
    margin: 0,
    padding: 0
  }

  const batchIcon = (val) => (
    <Popover content={<div className='custom-ant-popver-content'>点击可操作批量输入进行填充，也支持表格粘贴</div>}>
      <div onClick={() => handleBatchInput(val)}>
        <IconFont type="icondirect-input" style={{ fontSize: '13px', cursor: 'pointer' }} />
      </div>
    </Popover>
  )

  return (
    <div className={styles.gloablForm}>
      <Form
        form={form}
        size='middle'
        autoComplete="off"
        initialValues={{ ...query }}
        onFinish={onFinish}
        {...formConfig}
        style={{ ...formStyle, ...style }}
      >
        <Space size={12} wrap>
          {
            formArr.map((v, index) => {
              const { itemConfig, elConfig, formType } = v;
              const hide = (showExpand && !expand && !showKeys.includes(itemConfig.name)) ? true : false;
              if (hide) {
                return;
              }
              if (formType == 'inputGroup') {
                const { items = [] } = v;
                return (
                  <Form.Item style={formItemStyle} key={index}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      {
                        items.map(k => {
                          const { itemConfig, elConfig } = k;
                          const { batchInput, maxInputCount = 500, suffix, ...reset } = elConfig;
                          return (
                            <Form.Item style={formItemStyle} key={itemConfig.name} {...itemConfig}>
                              <FormContent {...{ ...reset, suffix: batchInput ? batchIcon(itemConfig.name) : suffix, handleSetForm }} />
                            </Form.Item>
                          )
                        })
                      }
                    </div>
                  </Form.Item>
                )
              }
              const { batchInput, maxInputCount = 500, suffix, ...reset } = elConfig;
              return (
                <Form.Item style={formItemStyle} key={index} {...itemConfig}>
                  <FormContent {...{ allowClear: true, ...reset, suffix: batchInput ? batchIcon(itemConfig.name) : suffix, handleSetForm }} />
                </Form.Item>
              )
            })
          }
          <Form.Item style={formItemStyle} colon={false} >
            <Space size={12} wrap>
              { showQuickSearch && expand && <QuickSearch { ...QuickSearchProps } />}
              {
                customSearchBtn ? 
                customSearchBtn :
                <Button
                  htmlType="submit"
                  type="primary"
                  icon={<IconFont type="iconsousuo" style={{ fontSize: '14px'}} />}
                  style={{ width: '64px', padding: 0, fontSize: '12px'}}
                >
                  搜索
                </Button>
              }
              <Button
                onClick={onReset}
                htmlType="reset"
                icon={<IconFont type="iconformReset" />}
                style={{ width: '64px', padding: 0, fontSize: '12px'}}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Space>
      </Form>
      {showExpand && (
        <div className={styles.expandWrap}>
          <div className={styles.expandContent} onClick={handleExpand}>
            {expand ? (
              <>
                <IconFont type="iconz045" />
                <span>收起</span>
              </>
            ) : (
              <>
                <IconFont type="iconzhankai" />
                <span>展开</span>
              </>
            )}
          </div>
        </div>
      )}
      {batchVisible && <BatchSearch {...searchProps} />}
    </div>
  )
}

export default FormRender;
